from wormbane.config.config import default_grid_size
from wormbane.geometry import Rectangle, Vector
from wormbane.engine.field_of_view import FieldOfView
from wormbane.model.thing import Thing, MoveError

class Level(Thing):
    is_level = True

    def __init__(self, size = default_grid_size):
        from wormbane.model.cell import Cell

        width, height = size
        self.size = Vector(width, height)
        self.inv = []
        self.bounds = Rectangle((0, 0), size)

        self.cells = {}
        for x in xrange(width):
            for y in xrange(height):
                Cell(pos = Vector(x, y)).move_to(self)

        self.rooms = []
        self.stair_up_pos = None
        self.stair_down_pos = None
        self.level_num = None
        self.monsters = set()
        self.field_of_view = FieldOfView(self)
        self.memory = [[' '] * width for y in xrange(height)]

    def __str__(self):
        width, height = self.size
        def char(x, y):
            return self.cells[Vector(x, y)].char
        def line(y):
            return ''.join(char(x, y) for x in xrange(width))
        return '\n'.join(line(y) for y in reversed(xrange(height))) + '\n'

    def add_inv(self, thing):
        if thing.is_cell and thing.pos in self.cells:
            raise MoveError(self, thing)
        Thing.add_inv(self, thing)
        if thing.is_cell:
            self.cells[thing.pos] = thing

    def remove_inv(self, thing):
        Thing.remove_inv(self, thing)
        if thing.is_cell:
            del self.cells[thing.pos]

    def add_monster(self, monster):
        self.monsters.add(monster)

    def remove_monster(self, monster):
        self.monsters.remove(monster)
